package jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/**
 * 实现用户登录功能
 * 程序启动后，要求用户输入用户名和密码
 * 然后去user表中查询该用户信息，如果用户名和密码与user表中记录一致则登录成功，否则登录失败
 *
 * 应当使用用户名和密码作为过滤条件去user表中查询信息，如果查询到记录则说明输入正确
 *
 * SELECT id,username,password,nickname,age
 * FROM user
 * WHERE username='xxxx' AND password='xxxx'
 *
 */
public class LoginDemo {
    public static void main(String[] args) {
        System.out.println("欢迎注册");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = scanner.nextLine();
        System.out.println("请输入密码:");
        String password = scanner.nextLine();
        /*
            用户名:gjhsadf
            密码:a' OR '1'='1

            SELECT id,username,password,nickname,age
            FROM user
            WHERE username='gjhsadf' AND password='a' OR '1'='1'
         */
        String sql = "SELECT id,username,password,nickname,age " +
                "FROM user " +
                "WHERE username='"+username+"' AND password='"+password+"'";
        System.out.println(sql);

        try (Connection connection = DBUtil.getConnection();){
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            if(rs.next()){
                String nickname = rs.getString("nickname");
                System.out.println("登录成功，欢迎【"+nickname+"】回来");
            }else{
                System.out.println("登录失败，用户名或密码不正确!");
            }


        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}







